<template>
  <div>
    <div class="splitLine"></div>
    <div class="ub">
      <div class="treeArea">
        <el-input size="small" style="margin-bottom: 10px;" v-model="filterText" placeholder="请输入目录名称"
          clearable></el-input>
        <el-tree class="tree" ref="tree" :data="treeData" node-key="id" :props="treeDefaultProps" :filter-node-method="(value, data) => {
          if (!value) return true
          return data.name.indexOf(value) !== -1
        }" @node-click="nodeClick" :default-expanded-keys="defaultExpandedKeys" :append-to-body="true">
        </el-tree>
      </div>
      <div class="ub-f1 tableArea">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
          <el-form-item label="上传时间">
            <el-date-picker value-format="yyyy-MM-dd" v-model="queryParams.dataTime" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="文件名称" prop="bucket">
            <el-input v-model="queryParams.name" placeholder="请输入文件名称" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-upload ref="uploadButton" class="uploadButton" drag multiple :action="uploadFileUrl"
          :before-upload="handleBeforeUpload" :headers="headers" :on-success="handleUploadSuccess" :data="{ projectId }"
          :showFileList="false" :limit="10">
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <el-table v-loading="loading" :data="list">
          <el-table-column label="序号" align="center" prop="index" width="50" />
          <el-table-column label="文件名称" align="center" prop="realName" />
          <el-table-column label="文件来源" align="center" prop="realName" />
          <el-table-column label="上传人" align="center" prop="createBy" />
          <el-table-column label="上传时间" align="center" prop="createTime" />
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button size="mini" type="text" @click="doPreview(scope.row)">预览</el-button>
              <el-button size="mini" type="text" @click="doDownload(scope.row)">下载</el-button>
              <el-button size="mini" type="text" @click="doDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import { getInforList, getFileList, appendAttaches } from "../api"
const Base64 = require("js-base64").Base64;
export default {
  name: "DetailList",
  data() {
    return {
      basePreviewUrl: process.env.VUE_APP_FILE_PREVIEW_BASE_API,
      orgName: "",
      filterText: "",
      selectNode: {},
      treeData: [],
      treeDefaultProps: {
        label: 'name',
        value: 'id'
      },
      defaultExpandedKeys: [],
      queryParams: {
        dataTime: [],
        name: ""
      },
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/safeUploader/uploadSafeDoc", // 上传文件服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      list: [],
      selectRow: {},
      loading: false,
      uploadDialogVisible: false,
      overFlog: false,
      form: {},
      // 自行上传
      unUploadFileNum: 0,
      // canDoUpload: true
    }
  },
  watch: {
    filterEnText(val) {
      this.$refs.tree.filter(val)
    }
  },
  computed: {
    projectId() {
      return this.$store.state.app.selectData
    }
  },
  created() {
    this.getTreeData()
  },
  methods: {
    nodeClick(data) {
      this.selectNode = data;
      if (data.createJunior == "0") {
        this.list = [];
        return;
      }
      this.getList();
    },
    async getList() {
      this.loading = true;
      const res = await getFileList({
        startTime: this.queryParams.dataTime.length ? this.queryParams.dataTime[0] : '',
        endTime: this.queryParams.dataTime.length ? this.queryParams.dataTime[1] : '',
        safeInforId: this.selectNode.id,
        fileName: this.queryParams.name,
        projectId: this.projectId
      });
      this.loading = false;
      this.list = res.data.rows.map((item, index) => ({ ...item, index: index + 1 }));
    },
    async getTreeData() {
      const res = await getInforList(this.projectId);
      this.treeData = this.handleTree(res.data, "id", "parentId");
    },
    handleQuery() {
      this.getList();
    },
    resetQuery() {
      this.queryParams.dataTime = [];
      this.queryParams.name = "";
      this.handleQuery();
    },
    handleBeforeUpload(file) {
      // if(!this.canDoUpload){
      //   return false
      // }
      if (this.selectNode.createJunior == "0") {
        this.$message.warning("当前节点不能上传文件，请核对后再进行添加文件")
        return false
      }
      // let fileExtension = "";
      // if (file.name.lastIndexOf(".") > -1) {
      //   fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
      // }
      // if (fileExtension.indexOf("jpeg") < 0) {
      //   this.$message.warning("只能上传jpeg格式的文件")
      //   return false;
      // }
      if (file.size > 5 * 1024 * 1024) {
        this.$message.warning("上传的文件大小不能超过5MB")
        this.canDoUpload = false
        return false;
      }
    },
    handleUploadSuccess(res, file) {
      let params = {
        safeInforId: this.selectNode.id,
        attachIds: [res.fileId]
      }
      appendAttaches(params).then(() => {
        this.$modal.msgSuccess("提交成功");
        this.getList();
        this.$emit("refresh")
      })
    },
    doPreview(row) {
      const url = this.basePreviewUrl + '?url=' + encodeURIComponent(Base64.encode(row.url)) + '&watermarkTxt=' + encodeURIComponent(this.orgName)
      window.open(url)
    },
    doDownload(row) {
      const url = row.url;
      window.open(url)
    },
    doDelete(row) {
      const attachId = row.id;
      this.$modal.confirm('是否确认删除文件编号为"' + attachId + '"的数据项？').then(function() {
        return delAttach(attachId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
        this.$emit("refresh")
      }).catch(() => {});
    }
  }
}
</script>
<style lang="scss" scoped>
.splitLine {
  margin-top: 10px;
  border: 1px solid #e0e0e0;
}

.treeArea {
  width: 300px;
  border-right: 1px solid #e0e0e0;
  padding-top: 10px;

  .tree {
    height: calc(100vh - 210px);
    overflow-y: auto;
  }
}

.tableArea {
  width: calc(100% - 300px);
  padding: 10px;

  .uploadButton {

    ::v-deep .el-upload,
    ::v-deep .el-upload-dragger {
      width: 100%;
      height: 120px;

      .el-icon-upload {
        margin-top: 20px;
      }
    }

  }
}
</style>